{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Microsoft Azure 人脸验证（主Find similar）\n",
    "\n",
    "- API文档：https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395237\n",
    "\n",
    "- 密钥：https://azure.microsoft.com/zh-cn/try/cognitive-services/my-apis/?apiSlug=face-api"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ①创建FaceList"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create_API文档：https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039524b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#创建FaceList\n",
    "\n",
    "# 导入模块\n",
    "import requests\n",
    "import json\n",
    "\n",
    "# 密钥\n",
    "subscription_key = \"045fdd4ec7554ffc939307077c1a534f\"\n",
    "assert subscription_key\n",
    "\n",
    "# 调用接口\n",
    "create_facelists_url = \"https://westcentralus.api.cognitive.microsoft.com/face/v1.0/facelists/{faceListId}\" \n",
    "\n",
    "# 请求表头\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "\n",
    "# 请求主体\n",
    "data = {\n",
    "    \"name\": \"try_list\", # FaceList的名字\n",
    "    \"userData\": \"User-provided data attached to the face list.\", # userData：此face为用户提供的数据附加到列表的face.\n",
    "    \"recognitionModel\": \"recognition_02\" # api文档建议选02，比01更精确\n",
    "}\n",
    "\n",
    "# 请求参数\n",
    "params = {     \n",
    "    \"faceListId\":\"try_12\" #注意运行后即已创建，不能重复创建同一个，否则会出现状态码为409\n",
    "}\n",
    "\n",
    "# PUT方法\n",
    "r_create = requests.put(create_facelists_url,headers=headers,params=params,json=data)\n",
    "r_create.status_code # 状态码"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ②往FaceList中Add Face"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add Face_API文档：https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395250"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n"
     ]
    }
   ],
   "source": [
    "# 往FaceList中Add Face\n",
    "\n",
    "# 导入模块\n",
    "import requests\n",
    "import json\n",
    "\n",
    "# 密钥\n",
    "subscription_key = \"045fdd4ec7554ffc939307077c1a534f\"\n",
    "assert subscription_key\n",
    "\n",
    "# 调用接口\n",
    "add_face_url =\"https://westcentralus.api.cognitive.microsoft.com/face/v1.0/facelists/{faceListId}/persistedFaces\"\n",
    "\n",
    "# 添加的图片的url\n",
    "# 阅读API文档注意到：targetFace只能含有一张人脸，0或多张均被视为错误\n",
    "# 总共添加了12张人脸进去(不要重复运行同一个url，否则依然添加)\n",
    "#add_face_image_url = \"https://wx2.sinaimg.cn/mw1024/005N9vhZgy1garl7rqmgaj31jq27m4qs.jpg\" \n",
    "#add_face_image_url = \"https://wx4.sinaimg.cn/mw1024/acff3e61ly3g9xqzvtjoij20rq0zkqg8.jpg\" \n",
    "#add_face_image_url = \"https://wx2.sinaimg.cn/mw1024/5ba8d1cbly1g8ngqigptjj22802s0npg.jpg\" \n",
    "#add_face_image_url = \"https://wx3.sinaimg.cn/mw1024/a1c3de7ely1gdsxnhytpoj20u0140n0w.jpg\" \n",
    "#add_face_image_url = \"https://wx1.sinaimg.cn/mw1024/86c8f8fcly1g8kpbzhfmjj20hs0lhqp0.jpg\" \n",
    "#add_face_image_url = \"https://wx4.sinaimg.cn/mw600/005Jq5lZgy1fisdrva6i0j30nm0z7wgc.jpg\" \n",
    "#add_face_image_url = \"https://wx1.sinaimg.cn/mw600/6a5d9573gy1gdpihb1nllj21kw184qci.jpg\" \n",
    "#add_face_image_url = \"https://wx2.sinaimg.cn/mw600/006xDZ8xgy1gdt07l4r65j318z0u0wl8.jpg\" \n",
    "#add_face_image_url = \"https://wx4.sinaimg.cn/mw1024/006ahIcxly1gde1or1r5sj33dj52aqvd.jpg\" \n",
    "#add_face_image_url = \"https://wx1.sinaimg.cn/mw1024/006VJhk2ly1gdmbwuxnsvj324g36onpe.jpg\" \n",
    "#add_face_image_url = \"https://wx3.sinaimg.cn/mw1024/006VJ5Jxly1gd1r2h1rujj33dw52ux6w.jpg\" \n",
    "add_face_image_url = \"https://wx1.sinaimg.cn/mw1024/006VXJ2Aly1gb83miv154j32v44aohe5.jpg\" \n",
    "\n",
    "# 请求表头\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "\n",
    "# 参数\n",
    "params_add_face={\n",
    "    \"userData\": \"RoyWang\",\n",
    "    \"faceListId\":\"try_12\"\n",
    "}\n",
    "\n",
    "# POST方法\n",
    "r_add_face = requests.post(add_face_url,headers=headers,params=params_add_face,json={\"url\":add_face_image_url})\n",
    "print(r_add_face.status_code)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ③在FaceList里检索上一步结果的具体信息"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " Get FaceList_API文档：https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039524c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'persistedFaces': [{'persistedFaceId': 'aff8c4c2-39f5-451c-ae8e-29a874b72e1a',\n",
       "   'userData': 'Kris'},\n",
       "  {'persistedFaceId': '89f08e50-b09f-455e-aefe-8f6d6cc2a8f7',\n",
       "   'userData': 'Victoria_Song'},\n",
       "  {'persistedFaceId': '0c16c03b-a396-40aa-a140-d3fa5f38390b',\n",
       "   'userData': 'Luhan'},\n",
       "  {'persistedFaceId': '3444bf72-b465-4d3f-9926-6c6e2304a4a6',\n",
       "   'userData': 'HZTao'},\n",
       "  {'persistedFaceId': 'c3d4ab05-23aa-4af9-995b-e24796a37c48',\n",
       "   'userData': 'Songzhixiao'},\n",
       "  {'persistedFaceId': '1f44ce78-3197-4cb8-b4d3-f33534d816fd',\n",
       "   'userData': 'LiuZS'},\n",
       "  {'persistedFaceId': '4668db45-b648-486b-9027-216ce6119ee9',\n",
       "   'userData': 'LiGuangZhu'},\n",
       "  {'persistedFaceId': 'bb63b37b-8cc4-40a3-8ef9-a8e46eb6e197',\n",
       "   'userData': 'Jackson_Wang'},\n",
       "  {'persistedFaceId': '815e4ad0-9047-40dc-942b-4d05722b5c6b',\n",
       "   'userData': 'BaiJT'},\n",
       "  {'persistedFaceId': '87ff92a1-221c-4af7-8952-f598bd6f5b8d',\n",
       "   'userData': 'JacksonYee'},\n",
       "  {'persistedFaceId': '02af96f0-1dd7-466b-99cc-f375297819db',\n",
       "   'userData': 'KarryWang'},\n",
       "  {'persistedFaceId': '67f534a5-8306-4553-b0c5-934a113f00bd',\n",
       "   'userData': 'RoyWang'}],\n",
       " 'faceListId': 'try_12',\n",
       " 'name': 'try_list',\n",
       " 'userData': 'User-provided data attached to the face list.'}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Get facelist\n",
    "\n",
    "# 官方提供的Request URL\n",
    "# https://{endpoint}/face/v1.0/facelists/{faceListId}[?returnRecognitionModel]\n",
    "\n",
    "# 密钥\n",
    "subscription_key = \"045fdd4ec7554ffc939307077c1a534f\"\n",
    "assert subscription_key\n",
    "\n",
    "# 调用接口\n",
    "get_facelist_url = \"https://westcentralus.api.cognitive.microsoft.com/face/v1.0/facelists/{faceListId}\"\n",
    "\n",
    "# 参数\n",
    "data = {\n",
    "    'returnRecognitionModel': 'false', #默认值\n",
    "    \"faceListId\":\"try_12\",\n",
    "}\n",
    "\n",
    "# GET方法\n",
    "r_get_facelist = requests.get(get_facelist_url,headers=headers,params=data)\n",
    "print(r_get_facelist.status_code)\n",
    "\n",
    "r_get_facelist.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ④Find Simliar前需先detect"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Detect_API文档：https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[{\"faceId\": \"9402f2f0-59d2-44ca-a2e7-4b22a559dcfc\", \"faceRectangle\": {\"top\": 177, \"left\": 504, \"width\": 157, \"height\": 157}, \"faceAttributes\": {\"smile\": 0.02, \"headPose\": {\"pitch\": -12.1, \"roll\": -7.6, \"yaw\": -2.4}, \"gender\": \"male\", \"age\": 21.0, \"facialHair\": {\"moustache\": 0.1, \"beard\": 0.1, \"sideburns\": 0.1}, \"glasses\": \"NoGlasses\", \"emotion\": {\"anger\": 0.001, \"contempt\": 0.001, \"disgust\": 0.001, \"fear\": 0.0, \"happiness\": 0.02, \"neutral\": 0.962, \"sadness\": 0.001, \"surprise\": 0.015}, \"blur\": {\"blurLevel\": \"medium\", \"value\": 0.51}, \"exposure\": {\"exposureLevel\": \"goodExposure\", \"value\": 0.52}, \"noise\": {\"noiseLevel\": \"medium\", \"value\": 0.54}, \"makeup\": {\"eyeMakeup\": true, \"lipMakeup\": true}, \"accessories\": [], \"occlusion\": {\"foreheadOccluded\": false, \"eyeOccluded\": false, \"mouthOccluded\": false}, \"hair\": {\"bald\": 0.02, \"invisible\": false, \"hairColor\": [{\"color\": \"black\", \"confidence\": 1.0}, {\"color\": \"other\", \"confidence\": 0.7}, {\"color\": \"brown\", \"confidence\": 0.57}, {\"color\": \"gray\", \"confidence\": 0.15}, {\"color\": \"red\", \"confidence\": 0.08}, {\"color\": \"blond\", \"confidence\": 0.03}]}}}]'"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 检测Add Face的图片的人脸ID\n",
    "\n",
    "# 官方提供的Request URL：\n",
    "# https://{endpoint}/face/v1.0/detect[?returnFaceId][&returnFaceLandmarks][&returnFaceAttributes][&recognitionModel][&returnRecognitionModel][&detectionModel]\n",
    "# 参数：[?returnFaceId][&returnFaceLandmarks][&returnFaceAttributes][&recognitionModel][&returnRecognitionModel][&detectionModel]\n",
    "\n",
    "# 密钥\n",
    "subscription_key = \"045fdd4ec7554ffc939307077c1a534f\"\n",
    "assert subscription_key\n",
    "\n",
    "# 调用接口\n",
    "detect_face_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'\n",
    "\n",
    "# 图片url（放了一张和'userData'为'Kris'的同一个人的不同图片）\n",
    "face_image_url = \"https://wx2.sinaimg.cn/mw1024/005N9vhZly1gbw1ce0q0ij31bx0qye81.jpg\" \n",
    "\n",
    "# 请求表头\n",
    "headers = {'Ocp-Apim-Subscription-Key': subscription_key}\n",
    "\n",
    "# 请求参数\n",
    "params = {\n",
    "    # API文档中的可选参数\n",
    "    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', # 可检测的全部属性\n",
    "    'returnFaceId': 'true', # 默认值\n",
    "    'returnFaceLandmarks': 'false', # 默认值\n",
    "    # 选择model\n",
    "    'recognitionModel':'recognition_02', # api文档建议选02，比01更精确\n",
    "    'detectionModel':'detection_01', # 默认值\n",
    "}\n",
    "\n",
    "# POST方法\n",
    "response = requests.post(detect_face_api_url, params=params,headers=headers,\n",
    "                         json={\"url\":face_image_url})\n",
    "print(response.status_code)\n",
    "\n",
    "# json.dumps 将json--->字符串\n",
    "json.dumps(response.json())\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ⑤Find Similar"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Find Similar_API文档：https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395237"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[{\"persistedFaceId\": \"aff8c4c2-39f5-451c-ae8e-29a874b72e1a\", \"confidence\": 0.91155}]'"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 密钥\n",
    "subscription_key = \"045fdd4ec7554ffc939307077c1a534f\"\n",
    "assert subscription_key\n",
    "\n",
    "# 调用接口\n",
    "findsimilars_url = \"https://westcentralus.api.cognitive.microsoft.com/face/v1.0/findsimilars\"\n",
    "\n",
    "# 请求表头\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "\n",
    "# 请求正文 \n",
    "data_findsimilars = {\n",
    "    \"faceId\":\"9402f2f0-59d2-44ca-a2e7-4b22a559dcfc\", # 前面detect出的faceId\n",
    "    \"faceListId\":\"try_12\",\n",
    "    \"maxNumOfCandidatesReturned\": 10, # 返回候选人的最大数量，默认值为20，这里选择10个\n",
    "    \"mode\": \"matchPerson\",  # 还有matchFace可选\n",
    "    }\n",
    "\n",
    "# POST方法\n",
    "r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)\n",
    "print(r_findsimilars.status_code)\n",
    "\n",
    "json.dumps(r_findsimilars.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "“匹配到的在FaceList中存在的FaceId” 正好就是  “userData为Kris的那张图片的FaceId”\n",
    "\n",
    "confidence（相似度）为91.155%"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "193.76px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
